<template>
  <div>
    <h1>水果清单</h1>
    <input v-model="newFruit.name" placeholder="水果名称" />
    <input v-model="newFruit.price" placeholder="单价" type="number" />
    <input v-model="newFruit.quantity" placeholder="数量" type="number" />
    <button @click="addFruit">添加</button>
    
    <ul>
      <li v-for="(fruit, index) in fruits" :key="index">
        {{ fruit.name }} 单价: {{ fruit.price }}  数量: {{ fruit.quantity }}
        <button @click="editFruit(index)">编辑</button>
        <button @click="removeFruit(index)">删除</button>
      </li>
    </ul>
    
    <div v-if="editingIndex !== null">
      <h3>编辑水果</h3>
      <input v-model="editedFruit.name" placeholder="水果名称" />
      <input v-model="editedFruit.price" placeholder="单价" type="number" />
      <input v-model="editedFruit.quantity" placeholder="数量" type="number" />
      <button @click="updateFruit">更新</button>
      <button @click="cancelEdit">取消</button>
    </div>
  </div>
</template>

<style>
  h1 {
    color: green;
  }

  ul {
    list-style-type: none;
    padding: 0;
  }

  li {
    margin: 5px 0;
  }

  input {
    margin-right: 10px;
  }
</style>

<script>
export default {
  data() {
    return {
      fruits: [
        { name: '苹果', price: 5, quantity: 10 },
        { name: '香蕉', price: 3, quantity: 20 },
        { name: '橙子', price: 4, quantity: 15 }
      ],
      newFruit: { name: '', price: null, quantity: null },
      editedFruit: { name: '', price: null, quantity: null },
      editingIndex: null
    };
  },
  methods: {
    addFruit() {
      if (this.newFruit.name.trim() !== '' && this.newFruit.price !== null && this.newFruit.quantity !== null) {
        this.fruits.push({ ...this.newFruit });
        this.newFruit = { name: '', price: null, quantity: null };
      }
    },
    removeFruit(index) {
      this.fruits.splice(index, 1);
    },
    editFruit(index) {
      this.editingIndex = index;
      this.editedFruit = { ...this.fruits[index] };
    },
    updateFruit() {
      if (this.editedFruit.name.trim() !== '' && this.editedFruit.price !== null && this.editedFruit.quantity !== null) {
        this.$set(this.fruits, this.editingIndex, { ...this.editedFruit });
        this.cancelEdit();
      }
    },
    cancelEdit() {
      this.editingIndex = null;
      this.editedFruit = { name: '', price: null, quantity: null };
    }
  }
};
</script>
